package main;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;

import towers.Tower;

public class Ticker implements Runnable {
	private final static long FPS=20;
	private final static long WAIT=1000/FPS;
	private Set<Tickable> ticks;
	private Set<Tickable> ticks2;
	private Set<Tickable> addList;
	
	public Ticker() {
		ticks = new HashSet<Tickable>();
		ticks2 = new HashSet<Tickable>();
		addList = new HashSet<Tickable>();
	}
	
	@Override
	public void run() {
		while (true) {
			long time = System.currentTimeMillis();
			
			for (Tickable t: ticks) {
				t.tick();
			}
			for (Tickable t: ticks2) {
				t.tick();
			}
			for (Tickable t: addList) {
				ticks.add(t);
			}
			addList = new HashSet<Tickable>();
			
			
			long left = WAIT-(System.currentTimeMillis()-time);
			if (left > 0) {
				try { Thread.sleep(left);
				} catch (InterruptedException e) { e.printStackTrace(); }
			}
		}
	}
	
	public void addTickable(Tickable t) {
		addList.add(t);
	}
	public void addPrio2(Tickable t) {
		ticks2.add(t);
	}

	public void add(Set<? extends Tickable> tickables) {
		addList.addAll(tickables);
	}
}
